﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using ReportWizard.Helpers;
using ReportWizard.Properties;

namespace ReportWizard.DataAccess
{
    public enum ToolPerferences
    {
        PathLogFile,
        PathReportFile,
        PathTemplateFile,
        PathGame,
        ParseImageTags,
        GroupSameTags,
        ViewPhotoListAsThumbnails
    }

    public class Perferences
    {
        public static string PathLogFile
        {
            get
            {
                string path = GetPerferenceValue(ToolPerferences.PathLogFile);
                return (FileSystem.CreateDirectory(path)) ? path : string.Empty;
            }
        }

        public static string PathReportFile 
        {
            get
            {
                string path = GetPerferenceValue(ToolPerferences.PathReportFile);
                return (FileSystem.CreateDirectory(path)) ? path : string.Empty;
            }
        }

        public static string PathTemplateFile
        {
            get
            {
                string path = GetPerferenceValue(ToolPerferences.PathTemplateFile);
                return (FileSystem.CreateDirectory(path)) ? path : string.Empty;
            }
        }

        public static string PathGame
        {
            get
            {
                return GetPerferenceValue(ToolPerferences.PathGame);
            }
        }

        public static string LogFileName
        {
            get { return string.Format("or_{0}.log", DateTime.Now.ToShortDateString()); }
        }

        public static bool ParseImageTags
        {
            get { return Convert.ToBoolean(GetPerferenceValue(ToolPerferences.ParseImageTags)); }
        }

        public static bool GroupSameTags
        {
            get { return Convert.ToBoolean(GetPerferenceValue(ToolPerferences.GroupSameTags)); }
        }

        public static bool ViewPhotoListAsThumbnails
        {
            get { return Convert.ToBoolean(GetPerferenceValue(ToolPerferences.ViewPhotoListAsThumbnails)); }
            set { Perferences.SetPerferenceValue(ToolPerferences.ViewPhotoListAsThumbnails, value.ToString()); }
        }

        public static bool CheckPerferences()
        {
            try
            {
                using (SqlConnection con = CommonDb.GetOilWizardConection())
                {
                    SqlCommand getCmd = new SqlCommand("PerferencesCheck", con);
                    getCmd.CommandType = CommandType.StoredProcedure;

                    getCmd.Parameters.Add("@UserId", SqlDbType.Int).Value = Globals.CurrentUser.Id;
                    getCmd.Parameters.Add("@ItemsCount", SqlDbType.Int).Direction = ParameterDirection.Output;
                    

                    con.Open();
                    getCmd.ExecuteNonQuery();
                    return Convert.ToInt32(getCmd.Parameters["@ItemsCount"].Value) == Enum.GetNames(typeof(ToolPerferences)).Length;
                }
            }
            catch (Exception ex)
            {
                Email.SendEmail(ex);
                return false;
            }
        }

        public static string GetPerferenceValue(ToolPerferences tp)
        {
            try
            {
                using (SqlConnection con = CommonDb.GetOilWizardConection())
                {
                    SqlCommand getCmd = new SqlCommand("PerferencesGet", con);
                    getCmd.CommandType = CommandType.StoredProcedure;

                    con.Open();
                    
                    getCmd.Parameters.Add("@UserId", SqlDbType.Int).Value = Globals.CurrentUser.Id;
                    getCmd.Parameters.Add("@Name", SqlDbType.VarBinary).Value = Crypto.Encrypt(tp);

                    getCmd.ExecuteNonQuery();

                    return Crypto.Decrypt((byte[])getCmd.ExecuteScalar());
                }
            }
            catch (Exception ex)
            {
                ShowMessage.Error(Resources.ApplicationWillBeClosedOnError);
                Process.GetCurrentProcess().Kill();
                throw;
            }
        }

        public static bool SetPerferenceValue(ToolPerferences tp, string perferenceValue)
        {
            try
            {
                using (SqlConnection con = CommonDb.GetOilWizardConection())
                {
                    SqlCommand setCmd = new SqlCommand("PerferencesSet", con);
                    setCmd.CommandType = CommandType.StoredProcedure;

                    setCmd.Parameters.Add("@UserId", SqlDbType.Int).Value = Globals.CurrentUser.Id;
                    setCmd.Parameters.Add("@Name", SqlDbType.VarBinary).Value = Crypto.Encrypt(tp);
                    setCmd.Parameters.Add("@Value", SqlDbType.VarBinary).Value = Crypto.Encrypt(!string.IsNullOrEmpty(perferenceValue) ? perferenceValue : string.Empty);

                    con.Open();
                    bool isRowsAffected = setCmd.ExecuteNonQuery() > 0;
                    if (isRowsAffected)
                    {
                        HistoryRecord hr = new HistoryRecord
                                               {
                                                   Action = HistoryEvent.PerferenceValueSet,
                                                   Description =
                                                       string.Format("[{0}]-[{1}]", tp, perferenceValue)
                                               };
                        hr.Insert();
                    }
                    return isRowsAffected;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                return false;
            }
        }

        public static void CreateDefaultPerferences()
        {
            try
            {
                using (SqlConnection con = CommonDb.GetOilWizardConection())
                {
                    SqlCommand saveCmd = new SqlCommand("PerferencesCreateDefault", con);
                    saveCmd.CommandType = CommandType.StoredProcedure;

                    saveCmd.Parameters.Add("@UserId", SqlDbType.Int).Value = Globals.CurrentUser.Id;

                    saveCmd.Parameters.Add("@NamePathLogFile", SqlDbType.VarBinary).Value = Crypto.Encrypt(ToolPerferences.PathLogFile);
                    saveCmd.Parameters.Add("@NamePathReportFile", SqlDbType.VarBinary).Value = Crypto.Encrypt(ToolPerferences.PathReportFile);
                    saveCmd.Parameters.Add("@NamePathTemplateFile", SqlDbType.VarBinary).Value = Crypto.Encrypt(ToolPerferences.PathTemplateFile);
                    saveCmd.Parameters.Add("@NamePathGame", SqlDbType.VarBinary).Value = Crypto.Encrypt(ToolPerferences.PathGame);
                    saveCmd.Parameters.Add("@NameParseImageTags", SqlDbType.VarBinary).Value = Crypto.Encrypt(ToolPerferences.ParseImageTags);
                    saveCmd.Parameters.Add("@NameGroupSameTags", SqlDbType.VarBinary).Value = Crypto.Encrypt(ToolPerferences.GroupSameTags);
                    saveCmd.Parameters.Add("@NameViewPhotoListAsThumbnails", SqlDbType.VarBinary).Value = Crypto.Encrypt(ToolPerferences.ViewPhotoListAsThumbnails);
                    

                    saveCmd.Parameters.Add("@ValuePathLogFile", SqlDbType.VarBinary).Value = Crypto.Encrypt(Path.Combine(Application.StartupPath, "Logs"));
                    saveCmd.Parameters.Add("@ValuePathReportFile", SqlDbType.VarBinary).Value = Crypto.Encrypt(Path.Combine(Application.StartupPath, "Reports"));
                    saveCmd.Parameters.Add("@ValuePathTemplateFile", SqlDbType.VarBinary).Value = Crypto.Encrypt(Path.Combine(Application.StartupPath, "Templates"));
                    saveCmd.Parameters.Add("@ValuePathGame", SqlDbType.VarBinary).Value = Crypto.Encrypt(string.Empty);
                    saveCmd.Parameters.Add("@ValueParseImageTags", SqlDbType.VarBinary).Value = Crypto.Encrypt(true);
                    saveCmd.Parameters.Add("@ValueGroupSameTags", SqlDbType.VarBinary).Value = Crypto.Encrypt(true);
                    saveCmd.Parameters.Add("@ValueViewPhotoListAsThumbnails", SqlDbType.VarBinary).Value = Crypto.Encrypt(false);

                    con.Open();
                    bool isRowsAffected = saveCmd.ExecuteNonQuery() > 0;
                    if (isRowsAffected)
                    {
                        HistoryRecord hr = new HistoryRecord
                        {
                            Action = HistoryEvent.PerferenceValueSet,
                            Description = string.Format(Resources.SetDefaultSettings)
                        };
                        hr.Insert();
                    }
                    ShowMessage.Info(Resources.SetDefaultSettings);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
    }
}
